from django.http import HttpResponse, JsonResponse
from rest_framework.pagination import PageNumberPagination
from rest_framework.views import APIView
from UShop.models import TbNews2
from news.serializer import NewsSerializer

#阅读新闻
class NewsDetailViewSet(APIView):
    def post(self,request,news_id):
        news_obj=TbNews2.objects.get(news_id=news_id)

        print('news_obj----',news_obj)
        new_serializer = NewsSerializer(news_obj)
        return JsonResponse(new_serializer.data)



#分页
class NewsP(PageNumberPagination):
    """
    配置分页规则
    """
    page_size=10
    page_size_query_param = 'page_size'
    page_query_param = "p"
    max_page_size = 100

class newsListView(APIView):
    """
    新闻列表
    """
    def get(self,request,):
        # print("*1111111")
        news=TbNews2.objects.all()
        # print("22222222222")
        newp = NewsP()
        page = newp.paginate_queryset(queryset=news, request=request, view=self )
        new_serializer = NewsSerializer(instance=page,many=True)
        return JsonResponse(new_serializer.data, safe=False)

#按分类显示新闻列表
class newscls(APIView):
    def post(self,request,news_classify)    :
        # print("11111")
        news_cls=TbNews2.objects.all().filter(news_classify=news_classify)
        # print("2222",news_cls)
        newp=NewsP()
        page=newp.paginate_queryset(queryset=news_cls,request=request,view=self)
        news_serializer=NewsSerializer(instance=page,many=True)
        # print("333",news_serializer)
        return JsonResponse(news_serializer.data, safe=False)

